package com.itheima.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("*******我是拦截器，你被拦截了！！preHandle AAAAAAAAA *******");
        //TODO 登录校验在此完成

        //1 获取请求路径url
        String url = request.getRequestURL().toString();
        //2 判断是否是登录请求
        if (url.contains("login")) {
            //登录，直接放行

            return true;
        }

        //3 获取请求头
        String jwt = request.getHeader("token");


        //4 判断是否存在token
        if (jwt == null) {
            notLoginResponse(response);

            //拦截
            return false;
        }

        //5 解析令牌
        try {
            Claims claims = JwtUtils.parseJWT(jwt);
            //放行
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            //令牌失效
            notLoginResponse(response);
            return false;
        }


    }

    /**
     * 返回结果
     *
     * @param servletResponse
     * @throws IOException
     */
    private void notLoginResponse(ServletResponse servletResponse) throws IOException {
        //返回统一NOT_LOGIN结果给前端
        Result errorResult = Result.error("NOT_LOGIN");
        //怎么把errorResult对象转换为JSON字符串？
        //java对象  JSON之间的映射
        ObjectMapper objectMapper = new ObjectMapper();
        //把java对象变成json字符串
        String json = objectMapper.writeValueAsString(errorResult);

        //返回到前端
        servletResponse.getWriter().write(json);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("*******我是拦截器，你被拦截了！！postHandle BBBBBBB *******");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("*******我是拦截器，你被拦截了！！afterCompletion CCCCCCCC *******");

    }
}
